package com.luyou.framework.security.config;


import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 *  Security 自动配置类，主要用于相关组件的配置
 * @author weiqi
 * @version 1.0
 * @date 2024/6/29 17:13
 * @desc
 */
@AutoConfiguration
@EnableConfigurationProperties(SecurityProperties.class)
public class LuyouSecurityAutoConfiguration implements WebMvcConfigurer {

    @Resource
    private SecurityProperties securityProperties;

    @Bean
    @Primary
    public SaTokenConfig getSaTokenConfigPrimary() {
        SaTokenConfig config = new SaTokenConfig();
        config.setTokenName(securityProperties.getTokenName());
        config.setTimeout(securityProperties.getTimeout());
        config.setActiveTimeout(securityProperties.getActiveTimeout());
        config.setIsConcurrent(securityProperties.getIsConcurrent());
        config.setIsShare(securityProperties.getIsShare());
        config.setTokenStyle(securityProperties.getTokenStyle());
        config.setIsLog(securityProperties.getIsLog());
        return config;
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
                .addPathPatterns("/**")
                .excludePathPatterns("/v3/api-docs/**")
                .excludePathPatterns("/swagger-ui/**")
                ;
    }
}
